package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ManageServiceImpl implements ManageService {
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;


    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(long category1Id) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>()
                .eq("category1_id", category1Id));

    }

    @Override
    public List<BaseCategory3> getCategory3(long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>()
                .eq("category2_id", category2Id));

    }

    @Override
    public List<BaseAttrInfo> getAttrInfoList(long category1Id, long category2Id, long category3Id) {
        return baseAttrInfoMapper.getAttrInfoList(category1Id, category2Id, category3Id);
    }

/*    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        if (baseAttrInfo.getId()==null){//id是空，则为添加
            //1.平台属性表
            baseAttrInfoMapper.insert(baseAttrInfo);
            //2.平台属性值表
            List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
            if (attrValueList != null && attrValueList.size()>0 ){
                attrValueList.forEach(attrValue ->{
                    //外键
                    attrValue.setAttrId(baseAttrInfo.getId());
                    baseAttrValueMapper.insert(attrValue);
                });
            }
        }else {//id不是空，则为修改
            QueryWrapper<BaseAttrValue> baseAttrValue = new QueryWrapper<BaseAttrValue>().eq("attr_id", baseAttrInfo.getId());
            baseAttrValueMapper.delete(baseAttrValue);
            List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
            if (attrValueList != null && attrValueList.size()>0 ){
                baseAttrInfoMapper.updateById(baseAttrInfo);
                attrValueList.forEach(attrValue ->{
                    //外键
                    attrValue.setAttrId(baseAttrInfo.getId());
                    baseAttrValueMapper.insert(attrValue);
                });
            }else {
                baseAttrInfoMapper.deleteById(baseAttrInfo);
            }

        }
    }*/


    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        if (baseAttrInfo.getId() == null) {//id是空，则为添加
            //1.平台属性表
            baseAttrInfoMapper.insert(baseAttrInfo);
        } else {//id不是空，则为修改
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }

        QueryWrapper<BaseAttrValue> baseAttrValue = new QueryWrapper<BaseAttrValue>().eq("attr_id", baseAttrInfo.getId());
        baseAttrValueMapper.delete(baseAttrValue);
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (attrValueList != null && attrValueList.size() > 0) {

            attrValueList.forEach(attrValue -> {
                //外键
                attrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(attrValue);
            });
        } else {
            baseAttrInfoMapper.deleteById(baseAttrInfo);
        }
    }


    @Override
    public BaseAttrInfo getAttrInfo(long attrId) {
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        return baseAttrInfo;
    }

    //品牌集合，分页查询
    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        return baseTrademarkMapper.selectPage(new Page<>(page, limit), null);

    }

    //查询商品集合分页
    @Override
    public IPage findSpuList(Integer page, Integer limit, Long category3Id) {
        return spuInfoMapper.selectPage(new Page<>(page, limit), new QueryWrapper<SpuInfo>().eq("category3_id", category3Id));
    }

    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);

    }

    //保存SPU
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {

        //1、商品表
        spuInfoMapper.insert(spuInfo);
        //2、图片表（总表）
        spuInfo.getSpuImageList().forEach(spuImage -> {
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);

        });
        //3、销售属性表
        spuInfo.getSpuSaleAttrList().forEach(spuSaleAttr -> {
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //4、销售属性值表
            spuSaleAttr.getSpuSaleAttrValueList().forEach(spuSaleAttrValue -> {
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });

        });


    }


    //sku中查询出所有图片，以供勾选
    @Override
    public List<SpuImage> spuImageList(Long spuId) {

        return spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));

    }


    //根据SPUID查询所有销售属性及属性值表
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }


    //添加sku，需要处理四张表
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //0：默认是下架状态，需要管理员审核物品的合法性
        skuInfo.setIsSale(SkuInfo.NOSALE);//硬编码问题
        //1:库存表
        skuInfoMapper.insert(skuInfo);
        //2:库存的图片表
        skuInfo.getSkuImageList().forEach(skuImage -> {
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
        //3:库存的平台 属性表
        skuInfo.getSkuAttrValueList().forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //4:库存的销售属性表
        skuInfo.getSkuSaleAttrValueList().forEach(skuSaleAttrValue -> {
            //skuId
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            //spuId
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
    }


    @Override
    public IPage skuList(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page<>(page, limit), null);
    }

    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ISSALE);
        skuInfoMapper.updateById(skuInfo);
        //TODO  将来 保存数据到ES中
    }

    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.NOSALE);
        skuInfoMapper.updateById(skuInfo);
        //TODO  将来 删除ES中数据
    }

    //下面是前端商品详情页功能：根据三级分类ID 查询一二三级分类
    @Override
    @GmallCache(prefix = "getBaseCategoryView")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    //2、查询Sku中的信息  sku_info  查询Sku中的图片  sku_image
    @Override
    @GmallCache(prefix = "getSkuInfo")  //加分布式缓存
    public SkuInfo getSkuInfo(long skuId) {
        //1、skuInfo  主键
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo != null){//保险起见，为了防止缓存穿透，加一层判断
            //2、skuImage 外键
            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
            skuInfo.setSkuImageList(skuImageList);
        }
        return skuInfo;
    }

    /*//2、查询Sku中的信息  sku_info  查询Sku中的图片  sku_image
    @Override
    @GmallCache(prefix = "getSkuInfo")  //加分布式缓存
    public SkuInfo getSkuInfo(long skuId) {
        //0:查询缓存：
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (null != skuInfo) {//缓存中有数据
            return skuInfo;
        } else {
            //解决缓存击穿问题，上分布式锁
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);
            //lock.lock();//不见不散

            *//*tryLock()参数解析：
            参数1：过期不侯 期的时间 过多久就不再获取锁了
            参数2：一旦获取到锁之后  锁的过期时间  防止死锁
            参数3：单位*//*
            try {
                boolean tryLock = lock.tryLock(1, 2, TimeUnit.SECONDS);//过期不候
                if (tryLock) {
                    //1:skuInfo 主键
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if (null != skuInfo) {
                        //2:skuImage 外键
                        List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                .eq("sku_id", skuId));
                        skuInfo.setSkuImageList(skuImageList);

                        //保存缓存中一份
                        //使用new Random().nextInt(300)：解决雪崩问题
                        redisTemplate.opsForValue().set(cacheKey, skuInfo, RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), TimeUnit.SECONDS);
                    } else {
                        //缓存穿透
                        skuInfo = new SkuInfo();//new一个空对象并返回，防止用户的恶意攻击
                        //解决穿透
                        redisTemplate.opsForValue().set(cacheKey, skuInfo, 5, TimeUnit.MINUTES);
                    }
                } else {
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
        return skuInfo;
    }*/


    /*//2、查询Sku中的信息  sku_info  查询Sku中的图片  sku_image
    @Override
    public SkuInfo getSkuInfo(long skuId) {
        //0:查询缓存：
        String cacheKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (null != skuInfo){//缓存中有数据
            return skuInfo;
        }else {//缓存中没有，取数据库查询

            //解决缓存击穿问题，上分布式锁
            String cacheLockKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
           //上分布式锁，设置过期时间
            String uuid = UUID.randomUUID().toString();
            Boolean isLock = redisTemplate.opsForValue().setIfAbsent(cacheLockKey, uuid,1,TimeUnit.SECONDS);
            if (isLock){
                //1:skuInfo 主键
                skuInfo = skuInfoMapper.selectById(skuId);
                if (null != skuInfo){
                    //2:skuImage 外键
                    List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                            .eq("sku_id", skuId));
                    skuInfo.setSkuImageList(skuImageList);

                    //保存缓存中一份
                    //使用new Random().nextInt(300)：解决雪崩问题
                    redisTemplate.opsForValue().set(cacheKey,skuInfo,RedisConst.SKUKEY_TIMEOUT+new Random().nextInt(300), TimeUnit.SECONDS);

                    //存完之后，删除锁(解锁)
                    //进行判断，防止误删
                    *//*String u = (String) redisTemplate.opsForValue().get(cacheLockKey);
                    if(uuid.equals(u)){//判断完后，删除之前，可能锁已经过期，此时别人可能已经拿到锁，此时删除的话，删除的是别人的锁，所以也需要优化
                        redisTemplate.delete(cacheLockKey);
                    }*//*

                    //释放锁：将上面的三句话捏合成一句执行，这样就不会有时差的问题了，并且redis是底层原子性的，在执行这句话的时候，不会被其他线程抢占
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                    this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList("lock"), uuid);

                }else {
                    //缓存穿透
                    skuInfo = new SkuInfo();//new一个空对象并返回，防止用户的恶意攻击
                    //解决穿透
                    redisTemplate.opsForValue().set(cacheKey,skuInfo,5, TimeUnit.MINUTES);

                }

            }else {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return (SkuInfo)redisTemplate.opsForValue().get(cacheKey);


            }
        }
        return skuInfo;
    }*/

    //3、查询价格
    @Override
    @GmallCache(prefix = "getPrice")
    public BigDecimal getPrice(long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo != null) {
            return skuInfo.getPrice();
        }
        return null;
    }


    //4、查询spu中总销售属性及属性值,同时选中一个默认商品 ( SQL相当难度 ）
    @Override
    @GmallCache(prefix = "getSaleAttrAndValueAndChecked")
    public List<SpuSaleAttr> getSaleAttrAndValueAndChecked(Long spuId, Long skuId) {
        return spuSaleAttrMapper.getSaleAttrAndValueAndChecked(spuId, skuId);
    }


    //5、查询页面上组合与skuId之间关系  { 1|5|7 ：skuId,1|4|7 : skuId } json格式的字符串
    //整数转String,Long转String有问题, 因此Long转成整数 再转String
    @Override
    @GmallCache(prefix = "getSkuValueIdsMap")
    public Map<Object, Object> getSkuValueIdsMap(Long spuId) {
        List<Map<Object, Object>> listMap = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        Map<Object, Object> result = new HashMap<>();
        listMap.forEach(map -> {
            result.put(map.get("value_ids"), map.get("sku_id"));
        });
        return result;
    }

    //首页,查询所有一二三级别分类视图
    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }

    ////据skuId 查询 sku_attr_value   base_attr_info  base_attr_value  三表联查
    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {

        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }


    private List<BaseAttrValue> getAttrValueList(Long attrId) {
        QueryWrapper queryWrapper = new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId);
        List<BaseAttrValue> baseAttrValueList = baseAttrValueMapper.selectList(queryWrapper);
        return baseAttrValueList;
    }

/*
    private void delAttrValueById(long AttrValueId){
        QueryWrapper<BaseAttrValue> attrValueQueryWrapper = new QueryWrapper<BaseAttrValue>().eq("id", AttrValueId);
        baseAttrValueMapper.deleteById(attrValueQueryWrapper);
    }
*/


}
